<template>
  <div>
    <!-- 添加批次按钮 -->
    <div style="display: flex; align-items: center; margin-bottom: 15px;">
      <el-button type="primary" @click="openAddDialog" style="margin-right: 10px;">添加批次</el-button>
    </div>

    <!-- 批次表格 -->
    <el-table :data="tableData" style="width: 100%">
      <!-- 序号列 -->
      <el-table-column label="序号" width="120">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>

      <!-- 批次名称 -->
      <el-table-column prop="name" label="批次名称" width="250"></el-table-column>

      <!-- 创建时间 -->
      <el-table-column prop="beginYear" label="创建时间" width="220"></el-table-column>

      <!-- 状态 -->
      <el-table-column prop="status" label="状态" width="150">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openEditDialog(row)" type="text" size="small">修改</el-button>
          <el-button @click="deleteBatch(row)" type="text" size="small" style="color: red;">删除</el-button>
          <el-button @click="viewParticipants(row)" type="text" size="small">查看参测人员</el-button>
          <el-button @click="addParticipants(row)" type="text" size="small">添加参测人员</el-button>
          <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="onSuccess"
              :on-error="onError"
              :disabled="importDisabled"
              style="display: inline-flex; margin-left: 20px;"
              :action="`/api/testPer/import/${row.id}`"> <!-- 使用模板字符串 -->
            <el-button size="small" :disabled="importDisabled" type="text" :icon="importDataIcon">
              {{ importDataText }}
            </el-button>
          </el-upload>



        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px;"
    ></el-pagination>

    <!-- 添加批次对话框 -->
    <el-dialog title="添加批次" :visible.sync="addDialogVisible">
      <el-form :model="newBatch" ref="addBatchForm">
        <el-form-item label="批次名称" prop="batchName">
          <el-input v-model="newBatch.name" required></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="newBatch.status" placeholder="请选择状态">
            <el-option label="激活" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addBatch">确定</el-button>
      </span>
    </el-dialog>

    <!-- 修改批次对话框 -->
    <el-dialog title="修改批次" :visible.sync="editDialogVisible">
      <el-form :model="currentBatch" ref="editBatchForm">
        <el-form-item label="批次名称" prop="batchName">
          <el-input v-model="currentBatch.name" required></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="currentBatch.status" placeholder="请选择状态">
            <el-option label="激活" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateBatch">确定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参测人员对话框 -->
    <el-dialog title="添加参测人员" :visible.sync="participantDialogVisible">
      <el-form :model="newParticipant" ref="addParticipantForm">
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="newParticipant.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" required>
          <el-input v-model="newParticipant.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="newParticipant.gender" placeholder="请选择性别">
            <el-option label="男" :value="'M'"></el-option>
            <el-option label="女" :value="'F'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="newParticipant.birthdate" type="date" placeholder="选择生日"></el-date-picker>
        </el-form-item>
        <el-form-item label="批次" prop="batchId">
          <el-input v-model="currentBatch.name" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="participantDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitParticipant">确定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import {getBatchPage, addBatch, deleteBatch, updateBatch, addParticipant, importParticipants} from '@/api/system/team'; // 导入 API 函数

export default {
  data() {
    return {
      // 导入按钮的文本
      importDataText: '导入数据',
      // 导入按钮的图标
      importDataIcon: 'el-icon-upload2',
      // 导入按钮是否被禁用
      importDisabled: false,
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      participantDialogVisible: false,
      newParticipant: {
        name: '',
        phone: '',
        gender: '',
        birthdate: '',
        teamId: ''
      },
      newBatch: {
        name: '',
        status: 1
      },
      currentBatch: {},
    };
  },
  created() {
    this.fetchBatches();
  },
  methods: {
    fetchBatches() {
      getBatchPage(this.currentPage, this.pageSize)
          .then(response => {
            this.tableData = response.data.records;
            this.total = response.data.total;
          })
          .catch(error => {
            console.error("获取批次数据失败:", error);
          });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchBatches();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchBatches();
    },
    openAddDialog() {
      this.newBatch = {}; // 重置新批次信息
      this.addDialogVisible = true;
    },
    addBatch() {
      addBatch(this.newBatch)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('批次添加成功！');
              this.addDialogVisible = false;
              this.fetchBatches();
            }
          })
          .catch(error => {
            console.error('添加批次失败:', error);
            this.$message.error('添加批次失败！');
          });
    },
    openEditDialog(batch) {
      this.currentBatch = { ...batch };
      this.editDialogVisible = true;
    },
    updateBatch() {
      updateBatch(this.currentBatch)
          .then(response => {
            this.$message.success('批次修改成功！');
            this.editDialogVisible = false;
            this.fetchBatches();
          })
          .catch(error => {
            console.error('修改批次失败:', error);
            this.$message.error('修改批次失败！');
          });
    },
    deleteBatch(batch) {
      this.$confirm('确定删除该批次吗?', '删除批次', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBatch(batch)
            .then(response => {
              this.$message.success('批次删除成功！');
              this.fetchBatches();
            })
            .catch(error => {
              console.error('删除批次失败:', error);
              this.$message.error('删除批次失败！');
            });
      });
    },
    viewParticipants(batch) {
      // 跳转到参测人员管理页面，并传递批次ID
      this.$router.push({ path: '/system/testPer', query: { batchId: batch.id} });
    },

    addParticipants(batch) {
      this.currentBatch = batch;
      this.newParticipant.teamId = batch.id; // 设置批次ID
      this.participantDialogVisible = true; // 打开对话框
    },
    submitParticipant() {
      console.log(this.newParticipant)
      addParticipant(this.newParticipant)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('参测人员添加成功！');
              this.participantDialogVisible = false; // 关闭对话框
              // 这里可以添加更新参测人员列表的逻辑
            } else {
              this.$message.error('添加参测人员失败！');
            }
          })
          .catch(error => {
            console.error('添加参测人员失败:', error);
            this.$message.error('添加参测人员失败！');
          });
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('请上传 Excel 文件！');
      }
      return isExcel;
    },
    handleFileChange(file) {
      console.log(this.newParticipant.teamId)
      importParticipants(this.currentBatch.id, file.raw) // 传递团队 ID 和文件
          .then(response => {
            if (response.code === 200) {
              this.$message.success('导入成功！');
              this.fetchBatches(); // 刷新批次数据
            } else {
              this.$message.error('导入失败！');
            }
          })
          .catch(error => {
            this.$message.error('导入失败！');
            console.error(error);
          });
    },
    onSuccess(response, file) {
      this.$message.success('导入成功！');
    },
    onError(error, file) {
      this.$message.error('导入失败！');
      console.error(error);
    },
    getStatusLabel(status) {
      return status === 1 ? '激活' : '禁用';
    },
  }
};
</script>

<style scoped>
.table-container {
  padding: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
